import axios from 'axios'
import store from '@/store/index'
import { reqRefreshToken } from '@/api/user'
import router from '@/router'
const instance = axios.create({
  baseURL: 'http://192.168.43.112:8000'
})
// 添加请求拦截器
instance.interceptors.request.use(function(config) {
  // 在发送请求之前做些什么
  const token = store.state.user.tokenInfo.token
  // 一定是token存在, 才携带, 如果请求中自己修改了Authorization字段, 用自己的
  if (token && !config.headers.Authorization) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, function(error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
instance.interceptors.response.use(function(response) {
  // 对响应数据做点什么
  return response.data
},
async function(error) {
  // 对响应错误做点什么
  console.dir(error)
  if (error.response.status === 401) {
    const refresh = store.state.user.tokenInfo.refresh_token
    if (refresh) {
      // 发请求刷新token
      try {
        const { data: { token }} = await reqRefreshToken(refresh)
        // console.log(token, '发请求刷新token')
        store.commit('user/setTokenInfo', {
          token,
          refresh_token: refresh
        })
        error.config.headers.Authorization = 'Bearer ' + token
        return instance(error.config)
      } catch {
        // 如果refresh也过期了就会跳登录页，登录后在跳转回来
        store.commit('user/removeTokenInfo')
        router.push({
          path: '/login',
          query: {
            backto: router.currentRoute.fullPath
          }
        })
      }
    }
    store.commit('user/removeToken')
    router.push({
      path: '/login',
      query: {
        backto: router.currentRoute.fullPath
      }
    })
    console.log(router.currentRoute)
  }
  return Promise.reject(error)
})
export default instance
